<template>
  <je-modal
    v-model:visible="visible"
    :title="modelTitle"
    :button-align="'center'"
    width="1000px"
    height="700px"
    class="je-modal-box"
    :resize="false"
    :maximizable="false"
  >
    <template #default style="height: 100%">
      <je-form
        v-if="visible"
        name="createForm"
        autocomplete="off"
        size="small"
        class="board-calendar-handle"
      >
        <je-form-item
          label="日程标题"
          name="CALENDAR_TITLE"
          v-bind="validateInfos.CALENDAR_TITLE"
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 20 }"
          validate-type="tooltip"
        >
          <je-input v-model:value="formState.CALENDAR_TITLE" placeholder="请输入标题..." />
        </je-form-item>
        <div class="form-item-group">
          <je-form-item
            label="全天"
            name="yesorno"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <je-select
              v-model:value="formState.CALENDAR_YESORNO_CODE"
              :options="dayTypeOptions"
              @change="changeDayType"
            />
          </je-form-item>
          <je-form-item
            label="类型"
            name="calendarType"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <je-select
              v-model:value="formState.CALENDAR_CALENDARTYPE_CODE"
              :options="calendarTypeOptions"
            />
          </je-form-item>
        </div>
        <div class="form-item-group">
          <je-form-item
            label="颜色"
            name="color"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <je-select v-model:value="formState.CALENDAR_COLOR" :options="colorTypeOptions" />
          </je-form-item>
          <je-form-item
            label="提醒时间"
            name="remindTime"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <je-date-picker
              v-model:value="formState['TEM_CALENDAR_REMIND_TIME']"
              :locale="locale"
              format="YYYY-MM-DD HH:mm"
              :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm') }"
            />
          </je-form-item>
        </div>
        <div class="form-item-group">
          <je-form-item
            label="开始时间"
            name="TEM_CALENDAR_STARTTIME"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
            v-bind="validateInfos.TEM_CALENDAR_STARTTIME"
            validate-type="tooltip"
          >
            <je-date-picker
              v-model:value="formState['TEM_CALENDAR_STARTTIME']"
              :allow-clear="allowClear"
              :locale="locale"
              :format="defaultFormatTime"
              :show-time="defaultShowTime"
              @change="handleChangeStartTime"
            />
          </je-form-item>
          <je-form-item
            label="结束时间"
            name="TEM_CALENDAR_ENDTIME"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
            v-bind="validateInfos.TEM_CALENDAR_ENDTIME"
            validate-type="tooltip"
          >
            <je-date-picker
              v-model:value="formState['TEM_CALENDAR_ENDTIME']"
              :allow-clear="allowClear"
              :locale="locale"
              :format="defaultFormatTime"
              :show-time="defaultShowTime"
              @change="handleChangeEndTime"
            />
          </je-form-item>
        </div>
        <je-form-item name="message">
          <je-row class="calendar-message">
            <je-col :span="3" class="calendar-message-label">
              <je-checkbox v-model:checked="messageChecked" @change="changeMessage">
                消息提醒：
              </je-checkbox>
            </je-col>
            <je-col :span="20">
              <je-checkbox-group
                v-model:value="formState.CALENDAR_MESSAGETYPE_CODE"
                :label-col="{ span: 3 }"
                :options="messageTypes.map((item) => ({ label: item.text, value: item.code }))"
              />
            </je-col>
          </je-row>
        </je-form-item>
        <je-form-item
          label="内容"
          name="notes"
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 20 }"
        >
          <je-editor-html v-model:value="formState.CALENDAR_NOTES" height="365" />
        </je-form-item>
      </je-form>
    </template>
    <template #buttons="modal">
      <je-row>
        <je-col>
          <je-button type="primary" :loading="btnLoading" @click="handleSave(modal)"
            >保存</je-button
          >
          <je-button
            v-show="!!formState.JE_SYS_CALENDAR_ID"
            :loading="btnLoading"
            class="handle-delete"
            @click="handleDelete"
          >
            删除
          </je-button>
          <je-button class="handle-cancel" @click="handleCancel(modal)">关闭</je-button>
        </je-col>
      </je-row>
    </template>
  </je-modal>
</template>

<script>
  import { defineComponent, reactive, toRefs, onMounted, watch, onBeforeUnmount } from 'vue';
  import locale from 'ant-design-vue/lib/date-picker/locale/zh_CN';
  import VueEvent from '@/helper/event';
  import dayjs from 'dayjs';
  import { Row, Col, DatePicker } from 'ant-design-vue';
  import { Modal, Form, Input, Button, Select, Checkbox, EditorHtml } from '@jecloud/ui';

  import { getCurrentUser } from '@jecloud/utils';
  import { GetMsDiyDicItem, SaveCalendar, RemoveCalendar, UpdateCalendar } from '@/api';
  import {
    HOME_CALENDAR_CREATE_VISIBLE,
    HOME_CALENDAR_EDIT_VISIBLE,
    HOME_CALENDAR_CLOSE_MODAL,
    HOME_CALENDAR_UPDATE_SUCCESS,
  } from '@/helper/constant';

  const useForm = Form.useForm;
  export default defineComponent({
    name: 'CalendarHandle',
    components: {
      JeModal: Modal,
      JeButton: Button,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeSelect: Select,
      JeInput: Input,
      JeRow: Row,
      JeCol: Col,
      JeDatePicker: DatePicker,
      JeCheckboxGroup: Checkbox.Group,
      JeEditorHtml: EditorHtml,
      JeCheckbox: Checkbox,
    },
    props: {
      selectDate: {
        type: String,
      },
    },
    setup(props) {
      // let curDay = dayjs().format('YYYY-MM-DD');
      const state = reactive({
        locale,
        dayjs,
        visible: false,
        btnLoading: false, //操作按钮loading
        modelTitle: '日程任务',
        messageChecked: false, //消息提醒
        defaultFormatTime: 'YYYY-MM-DD HH:mm', //时间默认显示格式
        defaultShowTime: { defaultValue: dayjs('YYYY-MM-DD', 'HH:mm') }, //选择时间时默认显示格式
        dayTypeOptions: [
          { label: '否', value: '0' },
          { label: '是', value: '1' },
        ],
        calendarTypeOptions: [
          { label: '日常记录', value: '1' },
          { label: '本周工作', value: '2' },
          { label: '下周工作', value: '3' },
        ],
        calendarTypeObj: {
          1: '日常记录',
          2: '本周工作',
          3: '下周工作',
        },
        colorTypeOptions: [
          { label: '红色', value: '#F6615D' },
          { label: '橙色', value: '#F8A646' },
          { label: '黄色', value: '#F4CE4B' },
          { label: '蓝色', value: '#386BD0' },
          { label: '绿色', value: '#6DCC51' },
          { label: '浅蓝', value: '#4BB8F3' },
          { label: '紫色', value: '#D088E1' },
        ],
        messageTypes: [], //消息提醒类型
        defaultMessageType: ['WEB', 'EMAIL', 'NOTE'], //默认选择消息类型类型
        temDeaultType: [], //根据类型返回结果默认过滤默认选中的选项
        messageAllType: '', //全部消息类型
        allowClear: false, //清除时间
        rulesRef: {
          CALENDAR_TITLE: [
            {
              required: true,
              message: '请输入标题',
            },
          ],
          TEM_CALENDAR_STARTTIME: [
            {
              required: true,
              message: '请选择开始时间',
            },
          ],
          TEM_CALENDAR_ENDTIME: [
            {
              required: true,
              message: '请选择结束时间',
            },
          ],
        },
        formState: {
          tableCode: 'JE_SYS_CALENDAR',
          CALENDAR_TITLE: '', //标题
          SY_CREATEUSERNAME: getCurrentUser()?.name, //创建人-当前登录用户
          SY_CREATEUSERID: getCurrentUser()?.id, //创建人id
          CALENDAR_YESORNO_CODE: '0', //全天
          CALENDAR_CALENDARTYPE_CODE: '1', //类型
          CALENDAR_CALENDARTYPE_NAME: '', //日历类型名称
          CALENDAR_COLOR: '#386BD0', //颜色 默认蓝色
          TEM_CALENDAR_STARTTIME: dayjs(props.selectDate + ' 08:00:00', 'YYYY-MM-DD HH:mm'), //开始时间 默认当日早上8点
          TEM_CALENDAR_ENDTIME: dayjs(props.selectDate + ' 18:00:00', 'YYYY-MM-DD HH:mm'), //结束时间 默认当日18点
          CALENDAR_STARTTIME: '', //开始时间 保存字段
          CALENDAR_ENDTIME: '', //结束时间 保存字段
          CALENDAR_REMIND_TIME: '', //提醒时间
          TEM_CALENDAR_REMIND_TIME: '', //提醒时间 显示字段
          CALENDAR_MESSAGETYPE_CODE: '', //消息提醒
          CALENDAR_NOTES: '', //内容
        },
      });
      const { resetFields, validate, validateInfos } = useForm(state.formState, state.rulesRef, {
        onValidate: (...args) => {},
      });
      const methods = {
        changeVisible() {
          //创建日程弹窗显示状态
          state.visible = true;
          resetFields();
          if (state.formState.JE_SYS_CALENDAR_ID) {
            delete state.formState.JE_SYS_CALENDAR_ID;
          }
          state.defaultFormatTime = 'YYYY-MM-DD HH:mm'; //时间默认显示格式
          state.defaultShowTime = { defaultValue: dayjs('00:00:00', 'HH:mm') }; //选择时间时默认显示格式
          state.formState.CALENDAR_MESSAGETYPE_CODE = ''; //清空通知方式code
          state.formState.TEM_CALENDAR_STARTTIME = dayjs(
            props.selectDate + ' 08:00:00',
            'YYYY-MM-DD HH:mm',
          );
          state.formState.TEM_CALENDAR_ENDTIME = dayjs(
            props.selectDate + ' 18:00:00',
            'YYYY-MM-DD HH:mm',
          );
          methods.getMessageTypes();
        },
        getMessageTypes() {
          //获取消息提醒类型
          const parms = {
            DICTIONARY_DDCODE: 'JE_WF_MESSAGETYPE',
          };
          GetMsDiyDicItem(parms).then((res) => {
            let temAllTypes = []; //配置的全部消息类型
            for (let item of res) {
              temAllTypes.push(item.code);
              if (state.defaultMessageType.includes(item.code)) {
                state.temDeaultType.push(item.code);
              }
            }
            state.formState.CALENDAR_MESSAGETYPE_CODE = state.temDeaultType.toString();
            state.messageAllType = temAllTypes.toString();
            //判断是否全选中
            if (temAllTypes.length === state.temDeaultType.length) {
              state.messageChecked = true;
            }
            state.messageTypes = res;
          });
        },
        handleSave(modal) {
          //保存操作
          state.btnLoading = true;
          validate()
            .then(() => {
              //比较开始和结束时间
              if (state.formState.CALENDAR_STARTTIME && state.formState.CALENDAR_ENDTIME) {
                const startDate = dayjs(state.formState.CALENDAR_STARTTIME); //开始时间
                const endDate = dayjs(state.formState.CALENDAR_ENDTIME); //结束时间
                const diffDate = endDate.diff(startDate, 'minute');
                if (diffDate < 0) {
                  Modal.alert('开始时间不能大于结束时间', 'warning');
                  state.btnLoading = false;
                  return;
                }
              }
              if (state.formState.CALENDAR_YESORNO_CODE == 1) {
                //当为全天方式时，开始和结束时间需要拼接时分
                state.formState.CALENDAR_STARTTIME =
                  state.formState.TEM_CALENDAR_STARTTIME.format('YYYY-MM-DD') + ' 00:00'; //开始时间
                state.formState.CALENDAR_ENDTIME =
                  state.formState.TEM_CALENDAR_ENDTIME.format('YYYY-MM-DD') + ' 23:59'; //结束时间
              } else {
                //不是全天方式
                state.formState.CALENDAR_STARTTIME =
                  state.formState.TEM_CALENDAR_STARTTIME.format('YYYY-MM-DD HH:mm');
                state.formState.CALENDAR_ENDTIME =
                  state.formState.TEM_CALENDAR_ENDTIME.format('YYYY-MM-DD HH:mm');
              }
              if (state.formState.TEM_CALENDAR_REMIND_TIME) {
                //提醒时间
                state.formState.CALENDAR_REMIND_TIME =
                  state.formState.TEM_CALENDAR_REMIND_TIME.format('YYYY-MM-DD HH:mm');
              } else {
                state.formState.CALENDAR_REMIND_TIME = '';
              }
              //提醒类型名称
              state.formState.CALENDAR_CALENDARTYPE_NAME =
                state.calendarTypeObj[state.formState.CALENDAR_CALENDARTYPE_CODE];
              if (state.formState.JE_SYS_CALENDAR_ID) {
                //编辑保存
                UpdateCalendar(state.formState).then((res) => {
                  if (res.code == 1000 && res.success) {
                    //关闭弹窗
                    methods.handleCancel();
                    state.btnLoading = false;
                    Modal.notice(res.message, 'success');
                    VueEvent.emit(HOME_CALENDAR_UPDATE_SUCCESS);
                  }
                });
              } else {
                //新增保存
                SaveCalendar(state.formState).then((res) => {
                  if (res.code == 1000 && res.success) {
                    //关闭弹窗
                    methods.handleCancel();
                    state.btnLoading = false;
                    Modal.notice(res.message, 'success');
                    VueEvent.emit(HOME_CALENDAR_UPDATE_SUCCESS);
                  }
                });
              }
            })
            .catch((err) => {
              state.btnLoading = false;
              console.log('error', err);
            });
          return false;
        },
        handleCancel() {
          //关闭弹窗
          if (state.formState.JE_SYS_CALENDAR_ID) {
            delete state.formState.JE_SYS_CALENDAR_ID;
          }
          resetFields(); //重置表单数据
          state.formState.CALENDAR_TITLE = ''; //标题
          state.defaultFormatTime = 'YYYY-MM-DD HH:mm'; //时间默认显示格式
          state.defaultShowTime = { defaultValue: dayjs('00:00:00', 'HH:mm') }; //选择时间时默认显示格式
          state.formState.CALENDAR_STARTTIME = dayjs(new Date()).format('YYYY-MM-DD') + ' 08:00'; //开始时间 默认当日早上8点
          state.formState.CALENDAR_ENDTIME = dayjs(new Date()).format('YYYY-MM-DD') + ' 18:00'; //结束时间 默认当日18点

          VueEvent.emit(HOME_CALENDAR_CLOSE_MODAL);
          state.visible = false;
        },
        handleDelete() {
          //删除日程
          Modal.alert({
            content: '确定要删除吗？',
            status: 'warning',
            okButton: () => {
              const param = {
                ids: state.formState.JE_SYS_CALENDAR_ID,
                tableCode: 'JE_SYS_CALENDAR',
              };
              RemoveCalendar(param).then((res) => {
                if (res.code == 1000 && res.success) {
                  Modal.notice(res.message, 'success');
                  methods.handleCancel();
                  VueEvent.emit(HOME_CALENDAR_UPDATE_SUCCESS);
                }
              });
            },
            cancelButton: () => {
              //关闭弹窗
            },
          });
        },
        editGetMessageType() {
          //编辑时获取消息提醒方式
          const parms = {
            DICTIONARY_DDCODE: 'JE_WF_MESSAGETYPE',
          };
          GetMsDiyDicItem(parms).then((res) => {
            state.messageTypes = res;
          });
        },
        editTask(task) {
          //监听编辑日程
          const parms = {
            DICTIONARY_DDCODE: 'JE_WF_MESSAGETYPE',
          };
          GetMsDiyDicItem(parms).then((res) => {
            state.messageTypes = res;
            state.formState.CALENDAR_TITLE = task.CALENDAR_TITLE; //标题
            state.formState.SY_CREATEUSERNAME = task.SY_CREATEUSERNAME; //创建人-当前登录用户
            state.formState.SY_CREATEUSERID = task.SY_CREATEUSERID; //创建人id
            state.formState.CALENDAR_YESORNO_CODE = task.CALENDAR_YESORNO_CODE; //全天
            state.formState.CALENDAR_CALENDARTYPE_CODE = task.CALENDAR_CALENDARTYPE_CODE; //类型
            state.formState.CALENDAR_CALENDARTYPE_NAME = task.CALENDAR_CALENDARTYPE_NAME; //日历类型名称
            state.formState.CALENDAR_COLOR = task.CALENDAR_COLOR; //颜色 默认蓝色
            state.formState.TEM_CALENDAR_STARTTIME = dayjs(task.CALENDAR_STARTTIME); //开始时间 显示字段
            state.formState.TEM_CALENDAR_ENDTIME = dayjs(task.CALENDAR_ENDTIME); //结束时间 显示字段
            state.formState.CALENDAR_STARTTIME = task.CALENDAR_STARTTIME; //开始时间 默认当日早上8点
            state.formState.CALENDAR_ENDTIME = task.CALENDAR_ENDTIME; //结束时间 默认当日18点
            state.formState.TEM_CALENDAR_REMIND_TIME = task.CALENDAR_REMIND_TIME
              ? dayjs(task.CALENDAR_REMIND_TIME)
              : ''; //提醒时间 显示字段
            state.formState.CALENDAR_REMIND_TIME = task.CALENDAR_REMIND_TIME; //提醒时间
            state.formState.CALENDAR_MESSAGETYPE_CODE = task.CALENDAR_MESSAGETYPE_CODE; //消息提醒
            state.formState.CALENDAR_NOTES = task.CALENDAR_NOTES; //内容
            state.formState.JE_SYS_CALENDAR_ID = task.JE_SYS_CALENDAR_ID; //主键id,编辑状态才有
            const messageCodeLength = task.CALENDAR_MESSAGETYPE_CODE.split(',').length;
            if (messageCodeLength == state.messageTypes.length) {
              state.messageChecked = true; //消息类型选中全选
            } else {
              state.messageChecked = false; //消息类型未选中全选
            }
            if (state.formState.CALENDAR_YESORNO_CODE == 1) {
              //当为全天方式时，开始和结束时间需要拼接时分
              state.defaultFormatTime = 'YYYY-MM-DD'; //时间默认显示格式
              state.defaultShowTime = null; //选择时间时默认显示格式
            }
            state.visible = true;
          });
        },
        changeMessage() {
          //监听消息提醒方式
          if (state.messageChecked) {
            state.formState.CALENDAR_MESSAGETYPE_CODE = state.messageAllType;
          } else {
            state.formState.CALENDAR_MESSAGETYPE_CODE = '';
          }
        },
        changeDayType() {
          //全天方式修改
          switch (state.formState.CALENDAR_YESORNO_CODE) {
            case '0': //否
              state.defaultFormatTime = 'YYYY-MM-DD HH:mm'; //时间默认显示格式
              state.defaultShowTime = { defaultValue: dayjs('00:00:00', 'HH:mm') }; //选择时间时默认显示格式
              if (state.formState.CALENDAR_STARTTIME) {
                //开始时间
                state.formState.CALENDAR_STARTTIME = dayjs(
                  state.formState.CALENDAR_STARTTIME,
                ).format('YYYY-MM-DD HH:mm');
              }
              if (state.formState.CALENDAR_ENDTIME) {
                //结束时间
                state.formState.CALENDAR_ENDTIME = dayjs(state.formState.CALENDAR_ENDTIME).format(
                  'YYYY-MM-DD HH:mm',
                );
              }
              break;
            case '1': //是
              state.defaultFormatTime = 'YYYY-MM-DD'; //时间默认显示格式
              state.defaultShowTime = null; //选择时间时默认显示格式
              if (state.formState.CALENDAR_STARTTIME) {
                //开始时间
                state.formState.CALENDAR_STARTTIME = dayjs(
                  state.formState.CALENDAR_STARTTIME,
                ).format('YYYY-MM-DD');
              }
              if (state.formState.CALENDAR_ENDTIME) {
                //结束时间
                state.formState.CALENDAR_ENDTIME = dayjs(state.formState.CALENDAR_ENDTIME).format(
                  'YYYY-MM-DD',
                );
              }
              break;
            default:
              break;
          }
        },
        handleChangeStartTime(val, mode) {
          //开始时间切换
          state.formState.CALENDAR_STARTTIME = dayjs(mode);
        },
        handleChangeEndTime(val, mode) {
          //结束时间切换
          state.formState.CALENDAR_ENDTIME = dayjs(mode);
        },
      };
      watch(
        //监听消息类型变化
        () => state.formState.CALENDAR_MESSAGETYPE_CODE,
        (newVal) => {
          if (newVal.split(',').length == state.messageTypes.length) {
            state.messageChecked = true;
          } else {
            state.messageChecked = false;
          }
        },
      ),
        onMounted(() => {
          // methods.getMessageTypes();
          VueEvent.on(HOME_CALENDAR_CREATE_VISIBLE, methods.changeVisible);
          VueEvent.on(HOME_CALENDAR_EDIT_VISIBLE, methods.editTask);
        });
      onBeforeUnmount(() => {
        VueEvent.off(HOME_CALENDAR_CREATE_VISIBLE);
        VueEvent.off(HOME_CALENDAR_EDIT_VISIBLE);
      });
      return {
        resetFields,
        validateInfos,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style>
  .je-modal-box .ant-picker-input > input:focus,
  .je-modal-box .ant-picker-input > input-focused {
    border-color: transparent;
    box-shadow: 0 0 0 0 transparent;
  }
  .je-modal-box .ant-picker-input > input:placeholder-shown {
    text-overflow: inherit;
  }
  .calendar-message .calendar-message-label {
    text-align: right !important;
  }
  .calendar-message .calendar-message-label .ant-checkbox + span {
    padding-right: 0 !important;
  }
  .je-modal-box .tox-tinymce {
    border: 1px solid #d9d9d9;
  }
  .je-modal-box .tox-tinymce .tox:not([dir='rtl']) .tox-toolbar__group:not(:last-of-type) {
    border: 1px solid #d9d9d9;
  }
</style>
<style scoped lang="less">
  .board-calendar-handle {
    margin: 5px 20px 0;
  }
  .board-calendar-handle::-webkit-scrollbar {
    width: 0;
    height: 0;
  }
  .board-calendar-handle .ant-form-item-control .ant-picker {
    width: 100%;
  }
  .je-modal-box .je-modal--footer .ant-row {
    width: 100%;
    justify-content: center;
    .handle-delete {
      border-color: #f19b2c;
      background-color: #f19b2c;
      color: #ffffff;
    }
    .handle-cancel {
      border-color: #dddddd;
      background-color: #f4f4f4;
      color: #444444;
    }
  }
  .calendar-message {
    align-items: center;
    .calendar-message-label .ant-checkbox + span {
      padding-right: 0;
    }
  }
  .form-item-group {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .ant-form-item {
      width: 50%;
    }
  }
  .form-item-single {
    width: 100%;
    display: flex;
    align-items: center;
  }
</style>
